package com.gs.commentvl.web.controller;

import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.simp.annotation.SendToUser;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.concurrent.ConcurrentTaskScheduler;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.gs.commentvl.model.Post;
import com.gs.commentvl.users.service.PostService;
import com.gs.commentvl.web.parameter.ParaGetData;
import com.gs.commentvl.web.parameter.Result;

@Controller
public class HomeController {

  private TaskScheduler scheduler = new ConcurrentTaskScheduler();
  private List<Stock> stockPrices = new ArrayList<Stock>();
  private Random rand = new Random(System.currentTimeMillis());

  @Autowired
  private PostService postService;

  /**
   * Iterates stock list, update the price by randomly choosing a positive
   * or negative percentage, then broadcast it to all subscribing clients
   */
//  private void updatePriceAndBroadcast() {
//    for(Stock stock : stockPrices) {
//      double chgPct = rand.nextDouble() * 5.0;
//      if(rand.nextInt(2) == 1) chgPct = -chgPct;
//      stock.setPrice(stock.getPrice() + (chgPct / 100.0 * stock.getPrice()));
//      stock.setTime(new Date());
//    }
//    template.convertAndSend("/topic/price", stockPrices);
//  }
//
//  /**
//   * Invoked after bean creation is complete, this method will schedule
//   * updatePriceAndBroacast every 1 second
//   */
//  @PostConstruct
//  private void broadcastTimePeriodically() {
//    scheduler.scheduleAtFixedRate(new Runnable() {
//      @Override public void run() {
//        updatePriceAndBroadcast();
//      }
//    }, 1000);
//  }
//
//  /**
//   * Handler to add one stock
//   */
//  @MessageMapping("/addStock")
//  public void addStock(Stock stock) throws Exception {
//    stockPrices.add(stock);
//    updatePriceAndBroadcast();
//  }
//
//  /**
//   * Handler to remove all stocks
//   */
//  @MessageMapping("/removeAllStocks")
//  public void removeAllStocks() {
//    stockPrices.clear();
//    updatePriceAndBroadcast();
//  }
//
//  /**
//   * Serve the main page
//   */
//  @RequestMapping(value = "/", method = RequestMethod.GET)
//  public String home() {
//    return "home";
//  }

//  @MessageMapping("/ws" )
//  @SendTo("/topic/showResult")
//  public Result addNum(CalcInput input) throws Exception {
//      Thread.sleep(2000);
//      Result result = new Result(input.getNum1()+"+"+input.getNum2()+"="+(input.getNum1()+input.getNum2()));
//      return result;
//  }

//***********************************************************************************************************

  @MessageMapping("/getPosts")
  //@SendTo("/topic/posts")
  @SendToUser("/queue/data")
  public Result getPost(ParaGetData input) {
	  long offset = input.getOffset();
	  long count = input.getCount() + 1;
	  Set<Post> lstPost = postService.getPostLimit(offset, count);
	  Result res = new Result();
	  if (lstPost.size() > input.getCount()) {
		  lstPost = postService.getPostLimit(offset, input.getCount());
		  res.setOffset(offset + count);
		  res.setFetch(true);
	  }
	  else {
		  res.setOffset(offset + lstPost.size());
		  res.setFetch(false);
	  }

	  res.setType("fetch");
	  res.setData(lstPost);
	  return res;
  }

  @MessageMapping("/firstLoad")
  @SendToUser("/queue/data")
  public Result fristLoad () {
	  Set<Post> lstPost = postService.getPostLimit(0, 11);

	  Result res = new Result();
	  if (lstPost.size() > 10) {
		  lstPost = postService.getPostLimit(0, 10);
		  res.setOffset(11);
		  res.setFetch(true);
	  }
	  else {
		  res.setOffset(lstPost.size());
		  res.setFetch(false);
	  }

	  res.setLength(lstPost.size());

	  //for testing...
	  //Set<Post> lstPost = postService.getPostLimit(0, -1);

	  res.setType("load");
	  res.setData(lstPost);
	  return res;
  }

  @MessageMapping("/addpost")
  @SendToUser("/queue/data")
  public Result addPost(Post post) {
	  Result res = new Result();
	  Post data = postService.addNewContent(post);
	  res.setType("add");
	  Set<Post> lstPost = new LinkedHashSet<Post>();
	  lstPost.add(data);
	  res.setData(lstPost);
	  res.setData(lstPost);
	  return res;
  }

//  @RequestMapping("/start")
//  public String start() {
//      return "start";
//  }

  @RequestMapping("/")
  public String start() {
      return "static/index.html";
  }

//  @RequestMapping("/index")
//  public String index() {
//      return "index";
//  }
}
